package com.elight.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTPUtils {
	// private Logger logger = Logger.getLogger(FTPUtils.class);
		private FTPClient ftpClient;
		private String ftpRoot = "/";

		/**
		 * 构造方法
		 * 
		 * @param ftpHost
		 * @param ftpPort
		 * @param ftpUserName
		 * @param ftpPassword
		 */
		public FTPUtils(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword) {
			try {
				ftpClient = new FTPClient();
				ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
				ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
				if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
					System.out.println("未连接到FTP，用户名或密码错误。");
					ftpClient.disconnect();
				} else {
					System.out.println("FTP连接成功。");
					// logger.info("FTP连接成功。");
				}
			} catch (SocketException e) {
				e.printStackTrace();
				System.out.println("FTP的IP地址可能错误，请正确配置。");
				// logger.info("FTP的IP地址可能错误，请正确配置。");
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("FTP的端口错误,请正确配置。");
				// logger.info("FTP的端口错误,请正确配置。");
			}
		}

		/**
		 * 默认21端口
		 * 
		 * @param ftpHost
		 * @param ftpUserName
		 * @param ftpPassword
		 */
		public FTPUtils(String ftpHost, String ftpUserName, String ftpPassword) {
			try {
				ftpClient = new FTPClient();
				ftpClient.connect(ftpHost, 21);// 连接FTP服务器
				ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
				if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
					System.out.println("未连接到FTP，用户名或密码错误。");
					// logger.info("未连接到FTP，用户名或密码错误。");
					ftpClient.disconnect();
				} else {
					System.out.println("FTP连接成功。");
					// logger.info("FTP连接成功。");
				}
			} catch (SocketException e) {
				e.printStackTrace();
				System.out.println("FTP的IP地址可能错误，请正确配置。");
				// logger.info("FTP的IP地址可能错误，请正确配置。");
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("FTP的端口错误,请正确配置。");
				// logger.info("FTP的端口错误,请正确配置。");
			}
		}

		/**
		 * 匿名登录
		 * 
		 * @param ftpHost
		 * @param port
		 */
		public FTPUtils(String ftpHost, int port) {
			try {
				ftpClient = new FTPClient();
				ftpClient.connect(ftpHost, port);// 连接FTP服务器
				ftpClient.login("anonymous", "zhoujunwen@ubearlie.com");// 登陆FTP服务器
				if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
					System.out.println("未连接到FTP，用户名或密码错误。");
					// logger.info("未连接到FTP，用户名或密码错误。");
					ftpClient.disconnect();
				} else {
					System.out.println("FTP连接成功。");
					// logger.info("FTP连接成功。");
				}
			} catch (SocketException e) {
				e.printStackTrace();
				System.out.println("FTP的IP地址可能错误，请正确配置。");
				// logger.info("FTP的IP地址可能错误，请正确配置。");
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("FTP的端口错误,请正确配置。");
				// logger.info("FTP的端口错误,请正确配置。");
			}
		}

		/**
		 * 匿名登录，默认21端口
		 * 
		 * @param ftpHost
		 */
		public FTPUtils(String ftpHost) {
			try {
				ftpClient = new FTPClient();
				ftpClient.connect(ftpHost, 21);// 连接FTP服务器
				ftpClient.login("anonymous", "zhoujunwen@ubearlie.com");// 登陆FTP服务器
				if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
					// logger.info("未连接到FTP，用户名或密码错误。");
					System.out.println("未连接到FTP，用户名或密码错误。");
					ftpClient.disconnect();
				} else {
					System.out.println("FTP连接成功。");
					// logger.info("FTP连接成功。");
				}
			} catch (SocketException e) {
				e.printStackTrace();
				System.out.println("FTP的IP地址可能错误，请正确配置。");
				// logger.info("FTP的IP地址可能错误，请正确配置。");
			} catch (IOException e) {
				e.printStackTrace();
				// logger.info("FTP的端口错误,请正确配置。");
				System.out.println("FTP的端口错误,请正确配置。");
			}
		}

		/**
		 * 退出登录ftp
		 * 
		 * @return
		 */
		public boolean logoutFtp() {
			try {
				if (ftpClient != null) {
					ftpClient.logout();
					ftpClient.disconnect();
				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println(e.getMessage());
			}
			return true;
		}

		/**
		 * 上传文件
		 * 
		 * @param strUrl
		 * @param file
		 * @return
		 */
		public boolean upload(String strUrl, File srcFile) {
			boolean flag = false;
			ftpClient.setControlEncoding("UTF-8");
			FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
			conf.setServerLanguageCode("zh");
			FileInputStream fis = null;
			try {
				fis = new FileInputStream(srcFile);
				// 设置上传目录
				ftpClient.changeWorkingDirectory(strUrl);
				ftpClient.setBufferSize(1024);
				ftpClient.setControlEncoding("UTF-8");
				// 设置文件类型（二进制）
				ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
				// 上传
				flag = ftpClient.storeFile(srcFile.getName(), fis);
				IOUtils.closeQuietly(fis);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				flag = false;
				System.out.println(e.getMessage());
				// e.printStackTrace();
			} catch (IOException e) {
				flag = false;
				System.out.println(e.getMessage());
				// TODO Auto-generated catch block
				// e.printStackTrace();
			}
			return flag;
		}

		public boolean download(String localPath, String remotePath, String fileName) {
			boolean flag = false;
			ftpClient.setControlEncoding("UTF-8");
			FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
			conf.setServerLanguageCode("zh");
			File localFile = new File(localPath + fileName);
			OutputStream os = null;
			try {
				os = new FileOutputStream(localFile);
				// retrieveFile的第一个参数需要是 ISO-8859-1 编码,并且必须是完整路径！
				flag = ftpClient.retrieveFile(remotePath + fileName, os);
				os.close();
			} catch (FileNotFoundException e) {
				System.out.println(e.getMessage());
				flag = false;
			} catch (IOException e) {
				System.out.println(e.getMessage());
				flag = false;
			}
			return flag;
		}

		/**
		 * 
		 * @param remoteDir
		 * @return
		 */
		public List<FTPFile> listFtpFile(String remoteDir) {
			ftpClient.setControlEncoding("UTF-8");
			FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
			conf.setServerLanguageCode("zh");
			List<FTPFile> list = new ArrayList<FTPFile>();
			try {
				FTPFile[] remoteFiles = ftpClient.listFiles(remoteDir);
				for (FTPFile f : remoteFiles) {
					if (f.isFile())
						list.add(f);
				}
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
			return list;
		}

		public List<String> listFtpDir(String remoteDir) {
			ftpClient.setControlEncoding("UTF-8");
			FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
			conf.setServerLanguageCode("zh");
			List<String> list = new ArrayList<String>();
			try {
				FTPFile[] remoteFiles = ftpClient.listFiles(remoteDir);
				for (FTPFile f : remoteFiles) {
					if (f.isDirectory())
						list.add(remoteDir + f.getName() + "/");
				}
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
			return list;
		}
}
